import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_juwo/common/common_index.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_juwo/provider/TaskIndex.dart';
import 'package:flutter_juwo/ui/custom/judje_dialog.dart';
import 'package:flutter_juwo/ui/model/version_entity.dart';
import 'package:flutter_juwo/ui/pages/personalCenterPages/ts/census/member.dart';
import 'package:flutter_juwo/ui/pages/personalCenterPages/ts/home/home.dart';
import 'package:flutter_juwo/ui/pages/personalCenterPages/ts/pushers/PusherSetting.dart';
import 'package:flutter_juwo/ui/pages/taskPages/Task.dart';
import 'package:flutter_juwo/ui/utils/toast_utils.dart';
import 'package:flutter_juwo/ui/utils/utils.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_juwo/ui/pages/personalCenterPages/PersionalCenterPage.dart';
import 'package:provider/provider.dart';
import 'package:url_launcher/url_launcher.dart';
import 'homePages/HomePage.dart';
import 'messagePages/MessageList.dart';
import 'personalCenterPages/ts/profit/profit.dart';

class BottomNavigationWidget extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => BottomNavigationWidgetState();
}

class BottomNavigationWidgetState extends State<BottomNavigationWidget> {
  PageController _controller;
  final double _iconWidth = 50;
  int _currentIndex = 0;
  List<Widget> list = List();
  int taskPageIndex = 0;

  @override
  void initState() {
    super.initState();
    checkVersion();
    _controller = PageController(initialPage: 0);
    init();
  }

  @override
  void dispose() {
    super.dispose();
    _controller.dispose();
  }

  @override
  Widget build(BuildContext context) {
    //ScreenUtil.instance = ScreenUtil(width: 750)..init(context);
    ScreenUtil.init(context, width: 750, allowFontScaling: false);
    return WillPopScope(
        child: DefaultTextStyle(
          style: CupertinoTheme.of(context).textTheme.textStyle,
          child: Scaffold(
            resizeToAvoidBottomPadding: false,
            body: Stack(
              children: <Widget>[
                Scaffold(
                  body: PageView(
                    controller: _controller,
                    physics: NeverScrollableScrollPhysics(),
                    children: list,
                  ),
                  bottomNavigationBar: CupertinoTabBar(
                    border: Border(
                      top: BorderSide(
                        color: Colours.c243,
                        width: ScreenUtil().setWidth(1), // One physical pixel.
                        style: BorderStyle.solid,
                      ),
                    ),
                    backgroundColor: Colors.white,
                    currentIndex: _currentIndex,
                    onTap: (int index) {
                      _controller.jumpToPage(index);
                      setState(() {
                        _currentIndex = index;
                      });
                    },
                    items: [
                      _bottomItem("首页", 0, 'icon_bottom_10', "icon_bottom_11"),
                      _bottomItem(
                          "会员统计", 1, 'icon_bottom_20', "icon_bottom_21"),
                      _bottomItem(
                          "收益统计", 2, 'icon_bottom_30', "icon_bottom_31"),
                      _bottomItem("推广人", 3, 'icon_bottom_30', "icon_bottom_31")
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),
        onWillPop: _doubleExit);
  }

  var _lastClickTime = 0;

  Future<bool> _doubleExit() {
    int nowTime = new DateTime.now().microsecondsSinceEpoch;
    if (_lastClickTime != 0 && nowTime - _lastClickTime > 1500) {
      return new Future.value(true);
    } else {
      ToastUtil.showShortToast('再按一次退出');
      _lastClickTime = new DateTime.now().microsecondsSinceEpoch;
      new Future.delayed(const Duration(milliseconds: 1500), () {
        _lastClickTime = 0;
      });
      return new Future.value(false);
    }
  }

  getTextStyle(bool isTab) {
    if (isTab) {
      return TextStyles.custom(24, Colours.cmain, Font.PingFangMedium);
    } else {
      return TextStyles.custom(24, Colours.c179, Font.PingFangMedium);
    }
  }

  jumpTo(value) {
    Provider.of<TaskIndexModel>(context).updatePhone(value);
    setState(() {
      taskPageIndex = value;
      _currentIndex = 1;
    });
    _controller.jumpToPage(1);
  }

  void init() {
    list.clear();
    list..add(PushHome())..add(Member())..add(Profit())..add(PusherSetting());
    //..add(TaskPage(taskPageIndex))
    //  ..add(MessageListPage())
    // ..add(PersonalCenter());
  }

  void checkVersion() {
    FormData params = FormData.from({"type": "Android"});
    DioManager.getInstance().get(Api.USER_VERSION, params, (json) {
      VersionEntity entity = VersionEntity.fromJson(json);
      if (null != entity && entity.code == 200) {
        if (int.parse("${entity.data.versionxl}") > Api.VERSION) {
          showElasticDialog(
              context: context,
              builder: (BuildContext context) {
                return WillPopScope(
                  child: JudjeDialog(
                    title: "发现新版本",
                    value: "发现新版本，请前往更新!",
                    onPressed: () {
                      _launchURL(entity.data.link);
                    },
                    onCancle: () async {
                      ///直接退出app
                      await pop();
                    },
                  ),
                  onWillPop: () async {
                    return Future.value(false);
                  },
                );
              });
        }
      }
    }, (err) {});
  }

  _launchURL(String link) async {
    if (await canLaunch(link)) {
      await launch(link);
    } else {
      throw 'Could not launch $link';
    }
  }

  static Future<void> pop() async {
    await SystemChannels.platform.invokeMethod('SystemNavigator.pop');
  }

  getImage(String name) {
    return Image.asset(
      Utils.getImgPath(name),
      width: ScreenUtil().setWidth(_iconWidth),
      height: ScreenUtil().setWidth(_iconWidth),
      fit: BoxFit.fill,
    );
  }

  _bottomItem(String name, int index, String icon0, String icon1) {
    return BottomNavigationBarItem(
        icon: getImage(icon0),
        activeIcon: getImage(icon1),
        title: Text(
          name,
          style:
              _currentIndex == index ? getTextStyle(true) : getTextStyle(false),
        ));
  }
}
